iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
3
自我挑戰組

JavaScript 試煉之旅系列 第 13

ES6 箭頭函式(arrow function)

  • 分享至 

  • xImage
  •  

今天要提的部分是關於 ES6 的新語法,箭頭函式(arrow function)。

它與 ES6 之前的函式(function)有著一些差別:

  • 箭頭函式(arrow function) 有著自己的特有寫法
  • 箭頭函式(arrow function) 沒有自己的this
  • 箭頭函式(arrow function) 沒有自己的arguments
  • 箭頭函式(arrow function) 不能用作建構式,因此沒有自己的prototype
  • 箭頭函式(arrow function)的 this 不因為使用 call() / apply() / bind() 方法而被修改

箭頭函式(arrow function)的特有寫法

箭頭函式有著全新樣貌的寫法,整理如下:

//第一種寫法
const arrowFunc = () => {console.log('test');}
//第二種寫法
const arrowFunc2 = a => {console.log(a);}
//第三種寫法
const arrowFunc3 = a => console.log(a);
//第四種寫法
const arrowFunc4 = (a,b) => {console.log(a+b);}
//第五種寫法
const arrowFunc5 = () => ({name:"Bill"});
  1. 如果沒有參數,可以只寫 (),如 arrowFunc
  2. 如果只有一個參數,可以不寫 (),如 arrowFunc2
  3. 如果程式碼行數只有單行,可以不需要 {},如 arrowFunc3,但如果為多行就需要 {}
  4. 如果有兩個參數以上,則必須寫 (),如 arrowFunc4
  5. 如果是物件格式,因為 {} 在箭頭函式中有意義, 所以必須要用 () 將整個物件包住,如arrowFunc5

箭頭函式(arrow function)沒有自己的this

因為箭頭函式沒有自己的 this,所以依照範疇鍊(scope chain)的觀念會往外層找。

來看看測試例子:

const obj = {
  name:'Jin',
  callName:function (){
    setTimeout(()=>{
       console.log(this);
       console.log(this.name);
    },1000)
  }
}
obj.callName();

setTimeout 裡面為一個箭頭函式(arrow function),所以會往外層作用域尋找 this 並拿來使用。

callName 作為方法被調用,所以 this 指向 obj(),因此箭頭函式的 this 指向 obj()

Day13-1
但如果是下面這個例子的話:

var name = 'Bill';
const obj = {
  name: 'Jin',
  callName:() => {
   console.log(this);
   console.log(this.name);
  }
}
obj.callName();

callName是一個箭頭函式,而且因為其外層作用域就是全域,所以 this 指向全域,也得到全域變數 name 的值 Bill

Day13-2

箭頭函式(arrow function)沒有arguments

直接看看箭頭函式與 ES6之前的函式使用 arguments 的差別

const arguments = [1, 2, 3];

const arr = () => arguments[0];
console.log(arr()); 

const arr2 = function(a,b){
    return arguments;
} 
console.log(arr2(1,2)); 

對於箭頭函式而言 arguments 只是單純的一個變數。但對於ES6之前的函式 arguments則是一個物件

Day13-3

箭頭函式(arrow function) 不能用作建構式,也沒有自己的prototype

var car = () => {};
var toyota = new car(); 

箭頭函式用於建構式會報錯。

Day13-4
也沒有自己的 prototype

var Foo = () => {};
console.log(Foo.prototype); 

Day13-5

箭頭函式(arrow function)的 this 不因為使用 call() / apply() / bind() 方法而被修改

const test = function(){
    console.log(this);
}
test.call('可以改變函式的this');

const test2 = () => {
    console.log(this);
}
test2.call('無法改變函式的this,而且this指向window物件');

可以看到箭頭函式的 this 指向全域,沒有因為使用 call() 方法而被修改

Day13-6

關於箭頭函式(arrow function)就先到這裡囉

明天見~


上一篇
JavaScript 函式(function)
下一篇
JavaScript 的 this 怎能不知道
系列文
JavaScript 試煉之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
RURU Tseng
iT邦新手 2 級 ‧ 2019-09-28 12:02:07

又是趕緊來觀摩鵬大筆記的一天~~~
/images/emoticon/emoticon42.gif

PH iT邦研究生 5 級 ‧ 2019-09-28 12:05:28 檢舉

哈哈XD

編大一PO文 我的筆記也同步做好了 感謝

PH iT邦研究生 5 級 ‧ 2019-09-28 12:47:41 檢舉

有這麼迅速~~XD

我要留言

立即登入留言